import { Model, DataTypes, Op, fn } from 'sequelize';
import db from '../db/mysql';

class PalaceUser extends Model {
  uuid: string;
  username: string;
  nickname: string;
  accessToken: string;
  mpDeviceToken: string;
  phonenumber: string;
  status: number;
  openId: string;
}

PalaceUser.init(
  {
    uuid: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING(100),
      defaultValue: '',
      comment: '用户名',
    },
    nickname: {
      type: DataTypes.STRING(200),
      defaultValue: '',
      comment: '昵称',
    },
    phonenumber: {
      type: DataTypes.STRING(20),
      defaultValue: '',
      comment: '手机号',
    },
    accessToken: {
      type: DataTypes.STRING(500),
      defaultValue: '',
      comment: 'accessToken',
    },
    mpDeviceToken: {
      type: DataTypes.STRING(500),
      defaultValue: '',
      comment: 'mpDeviceToken',
    },
    openId: {
      type: DataTypes.STRING(100),
      defaultValue: '',
      comment: 'openId',
    },
    status: {
      type: DataTypes.TINYINT({ length: 1 }),
      defaultValue: 1,
      comment: '状态',
    },
  },
  {
    sequelize: db,
    freezeTableName: true,
    tableName: 't_palace_user',
    indexes: [
      {
        fields: ['phonenumber'],
      },
      {
        fields: ['phonenumber', 'username'],
      },
    ],
  }
);

//强制初始化数据库
// PalaceUser.sync({ force: true });

export default {
  sync(force = true) {
    return PalaceUser.sync({ force });
  },
  insert: function (model: any) {
    return PalaceUser.create(model);
  },
  update(data, uuid) {
    return PalaceUser.update(data, { where: { uuid } });
  },
  findOne(phoneNumber: string) {
    return PalaceUser.findOne({ where: { phonenumber: phoneNumber }, attributes: ['username', 'uuid', 'status'] });
  },
  findOneAvailable() {
    return PalaceUser.findOne({
      where: { status: 1 },
      order: [fn('RAND')],
      attributes: ['username', 'uuid', 'phonenumber', 'accessToken', 'openId', 'mpDeviceToken']
    });
  },
  getlist(pageindex: number, phoneNumber?: string) {
    let opts: any = {};
    if (phoneNumber) {
      opts.phonenumber = phoneNumber;
    }
    opts.status = 1;
    return PalaceUser.findAndCountAll({
      where: opts,
      order: [['updatedAt', 'desc']],
      limit: 20,
      offset: (pageindex - 1) * 20,
      attributes: ['uuid', 'nickname', 'username', 'phonenumber', 'updatedAt', 'accessToken'],
    });
  },
  delList(ids: string[]) {
    return PalaceUser.destroy({
      where: {
        uuid: {
          [Op.in]: ids,
        },
      },
    });
  },
};
